package com.bao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.jdbc.datasource.init.ScriptUtils;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.sql.SQLException;

@SpringBootApplication
public class RunApp {
    @Autowired
    private DataSource dataSource;
    public static void main(String[] args) {
        SpringApplication.run(RunApp.class,args );
    }

    @PostConstruct
    public void init(){
        exec("sql/account.sql");
        exec("sql/order.sql");
        exec("sql/seata-server.sql");
        exec("sql/storage.sql");
    }

    private void exec(String sql) {
        ClassPathResource cpr = new ClassPathResource(sql, RunApp.class.getClassLoader());
        EncodedResource encodedResource = new EncodedResource(cpr, "UTF-8");
        //spring执行脚本文件的方法
        try {
            ScriptUtils.executeSqlScript(dataSource.getConnection(),encodedResource );
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
